<?php

declare(strict_types=1);

namespace app\wechat\controller\admin;

use think\Request;
use think\Response;
use sheep\controller\Backend;
use app\wechat\facade\Wechat;
use Ramsey\Uuid\Uuid;
use sheep\model\ThirdOauth;

class User extends Backend
{

    protected $wechat = null;

    public function initialize()
    {
        $this->wechat = Wechat::officialAccount();
    }

    public function getQrcode(Request $request)
    {
        $event = $request->param('event');

        if (!in_array($event, ['login', 'bind'])) {
            return error('参数错误');
        }

        // 二维码和缓存过期时间
        $expireTime = 1 * 60;

        // 事件唯一标识
        $eventId = Uuid::uuid4();

        $cacheKey = "wechatAdmin.${event}.${eventId}";

        cache($cacheKey, ['id' => 0], $expireTime);

        $result = $this->wechat->qrcode->temporary($cacheKey, $expireTime);

        $qrcode = $this->wechat->qrcode->url($result['ticket']);

        return success('', [
            'url' => $qrcode,
            'eventId' => $eventId
        ]);
    }

    public function checkScan(Request $request)
    {
        $event = $request->param('event');
        $eventId = $request->param('eventId');

        if (!in_array($event, ['login', 'bind'])) {
            return error('参数错误');
        }

        $cacheKey = "wechatAdmin.${event}.${eventId}";

        $cacheValue = cache($cacheKey);

        if (empty($cacheValue)) {
            return error('二维码已过期, 请重新扫码');
        }

        if ($cacheValue['id'] === 0) {
            return error('等待扫码', -1);
        }

        if ($cacheValue['id'] !== 0) {
            switch ($event) {
                case 'login':
                    $this->auth()->loginUsingId($cacheValue['id']);
                    break;
                case 'bind':
                    $adminId = $this->auth()->user()->id;

                    $thirdOauth = ThirdOauth::where([
                        'provider' => 'wechat',
                        'platform' => 'admin',
                        'admin_id' => $adminId
                    ])->find();
                    
                    if($thirdOauth) {
                        return error('该管理员已绑定其他微信账号');
                    }
                    
                    $thirdOauth = ThirdOauth::create([
                        'provider' => 'wechat',
                        'platform' => 'admin',
                        'openid' => $cacheValue['id'],
                        'admin_id' => $adminId
                    ]);
                    break;
            }
            return success();
        }
    }
}
